package com.sky.aop;

import com.sky.annotation.AutoFillInsert;
import com.sky.annotation.AutoFillUpdate;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Objects;

/**
 * 自动注入AOP
 *
 * @author liudo
 * @version 1.0
 * @project sky-take-out
 * @date 2023/12/5 09:27:52
 */
@Slf4j
@Component
@Aspect
public class AutoFillAop {

    @Pointcut("@annotation(com.sky.annotation.AutoFillInsert) || " +
            "@annotation(com.sky.annotation.AutoFillUpdate)")
    public void pt() {
    }

    @Before("pt()")
    public void autoFill(JoinPoint joinPoint) {
        log.info("---------拦截到了---------");
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        // 获取方法上的注解
        AutoFillInsert autoFillInsert = method.getAnnotation(AutoFillInsert.class);

        try {
            // 区分是新增 - 四个属性的填充
            Object[] args = joinPoint.getArgs();
            Object param = args[0];
            // 获取类的 Class 对象
            Class<?> clazz = param.getClass();
            Method setUpdateTime = clazz.getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method setUpdateUser = clazz.getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

            // 调用 setValue 方法
            setUpdateTime.invoke(param, LocalDateTime.now());
            setUpdateUser.invoke(param, BaseContext.getCurrentId());

            if (Objects.nonNull(autoFillInsert)) {
                Method setCreateTime = clazz.getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = clazz.getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);

                // 调用 setValue 方法
                setCreateTime.invoke(param, LocalDateTime.now());
                setCreateUser.invoke(param, BaseContext.getCurrentId());
            }
        } catch (Exception e) {
            log.error("--------自动注入失败---------", e);
        }
    }
}
